[Coding026] Sort - 桶排序

Bucket-sort

Ben 2024/01/17

More coding records

Get the knowledge flowing and circulating! :)

目录

标题:桶排序

image-20240117131039683

桶排序(英语:Bucket sort)或所谓的箱排序,是一个排序算法,工作的原理是将数组分到有限数量的桶里。每个桶再个别排序(有可能再使用别的排序算法或是以递归方式继续使用桶排序进行排序)。桶排序是鸽巢排序的一种归纳结果。当要被排序的数组内的数值是均匀分配的时候,桶排序使用线性时间(Θ(n))。

桶排序以下列程序进行:

  1. 设置一个定量的数组当作空桶子。

  2. 寻访序列,并且把项目一个一个放到对应的桶子去。

  3. 对每个不是空的桶子进行排序。

  4. 从不是空的桶子里把项目再放回原来的序列中。

——维基百科

补充笔记

DefinitionStable sorting algorithm

A sorting algorithm that preserves the order of items with identical key。

INPUT: (1,x), (6,m), (4,k), (5,t), (2,s), (3,b), (1,a), (6,f), (6,b) → 解释:(3, b)中,3是key,b是object

Example of stable output:

OUTPUT: (1,x), (1,a), (2,s), (3,b), (4,k), (5,t), (6,m), (6,f), (6,b)


问题:至今似乎我们看到的排序最好的时间复杂度为O(nlogn),有没有可能还有更好的排序算法呢?

回答:没了。一般来说,Ω(nlogn)的问题有一个下界,但是在某些情况下,O(n)也是可能的。

桶排序 vs Others

Imagine putting 200 student papers in alphabetical order according to the first letter of the last name. An insertion sort (or selection sort, or bubbleSort) would have us try to deal with the whole pile at once. Merge-sort would require spreading out all 200 papers and then comparing and piling them back up again in order.

想象一下,把200名学生的论文按照姓氏的首字母顺序排列。插入排序(或选择排序,或冒泡排序)会让我们尝试一次处理整个堆。归并排序需要将所有200份文件展开,然后再按顺序进行比较和堆积。

Bucket-Sort has us place them into 26 piles by first letter and then stacking those piles together.

桶式排序让我们按照首字母将它们分成26堆,然后将这些摞在一起。

桶排序思想和复杂度

Bucket-sort takes O(n+N) time.

算法伪代码(Pseudo-code)

image-20240119113650910

实际案例

image-20240119114240382

特性(Properties)

Key-type Property(键的类型的性质)

Stable Sort Property(排序的稳定性)

拓展(Extensions)

实例

image-20240119115114147